/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package naptanparser;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;

/**
 *
 * @author david
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static List<GPSPoint> points = new ArrayList<GPSPoint>();

    public static void main(String[] args) {
        // parseFile();
        generateTimes();

    }

    public static void PolygonSearch() {
        //A little test

        GPSPoint outside = new GPSPoint(51.5072, -2.6308);
        boolean result = pointInPolygon(points, outside.getLatitude(), outside.getLongitude());
        System.out.println(result);
        GPSPoint inside = new GPSPoint(51.47605, -2.616309);
        result = pointInPolygon(points, inside.getLatitude(), inside.getLongitude());
        System.out.println(result);
        inside = new GPSPoint(51.492, -2.6164);
        result = pointInPolygon(points, inside.getLatitude(), inside.getLongitude());
        System.out.println(result);
        inside = new GPSPoint(51.4791, -2.6284);
        result = pointInPolygon(points, inside.getLatitude(), inside.getLongitude());
        System.out.println(result);

    }

    public static boolean pointInPolygon(List<GPSPoint> points, Double lat, Double lon) {
        //Modified from http://msdn.microsoft.com/en-us/library/cc451895.aspx#
        int i = 0;
        int j = points.size() - 1;

        boolean inPoly = false;

        for (i = 0; i < points.size(); i++) {
            if (points.get(i).getLongitude() < lon && points.get(j).getLongitude() >= lon || points.get(j).getLongitude() < lon && points.get(i).getLongitude() >= lon) {
                if (points.get(i).getLatitude() + (lon - points.get(i).getLongitude()) /
                        (points.get(j).getLongitude() - points.get(i).getLongitude()) * (points.get(j).getLatitude() - points.get(i).getLatitude()) < lat) {
                    inPoly = !inPoly;
                }
            }
            j = i;
        }
        return inPoly;
    }

    private static void parseFile() {
        //OLD POINT BELOW 352 vertices
        points.add(new GPSPoint(51.447631, -2.59552));
        points.add(new GPSPoint(51.482709, -2.612));
        points.add(new GPSPoint(51.517973, -2.68959));
        points.add(new GPSPoint(51.493184, -2.719803));
        points.add(new GPSPoint(51.456189, -2.663155));
        points.add(new GPSPoint(51.447631, -2.59552));
        // new points
        points.clear();
        points.add(new GPSPoint(51.447631, -2.59552));


        points.add(new GPSPoint(51.501701, -2.700834));
        points.add(new GPSPoint(51.495289, -2.679205));
        points.add(new GPSPoint(51.490854, -2.676029));
        points.add(new GPSPoint(51.490266, -2.669764));
        points.add(new GPSPoint(51.491709, -2.665987));
        points.add(new GPSPoint(51.492671, -2.655602));
        points.add(new GPSPoint(51.494755, -2.645302));
        points.add(new GPSPoint(51.492778, -2.636375));
        points.add(new GPSPoint(51.486044, -2.629337));
        points.add(new GPSPoint(51.480859, -2.619982));
        points.add(new GPSPoint(51.478026, -2.614746));
        points.add(new GPSPoint(51.468189, -2.610884));
        points.add(new GPSPoint(51.462735, -2.606592));
        points.add(new GPSPoint(51.463056, -2.599125));
        points.add(new GPSPoint(51.459098, -2.597237));
        points.add(new GPSPoint(51.455408, -2.597408));
        points.add(new GPSPoint(51.453911, -2.605648));
        points.add(new GPSPoint(51.456852, -2.610798));
        points.add(new GPSPoint(51.460061, -2.611914));
        points.add(new GPSPoint(51.465515, -2.613974));
        points.add(new GPSPoint(51.477438, -2.619553));
        points.add(new GPSPoint(51.478293, -2.62393));
        points.add(new GPSPoint(51.478186, -2.651482));
        points.add(new GPSPoint(51.483157, -2.681351));
        points.add(new GPSPoint(51.492243, -2.693796));
        points.add(new GPSPoint(51.501701, -2.700834));

        try {
            File file = new File("naptan-bristol.xml");
            FileInputStream fis = new FileInputStream(file);
            System.out.println("File Size:" + file.getTotalSpace());
            XMLInputFactory factory = XMLInputFactory.newInstance();
            XMLStreamReader parser = factory.createXMLStreamReader(fis);
            FileWriter fstream = new FileWriter("stops.txt");
            BufferedWriter outfile = new BufferedWriter(fstream);

            //Close the output stream

            int x = 0;
            int stops = 0;
            String stopid = "", lon = "", lat = "", name = "", id = "", landmark = "", street = "";
            Double longitude, latitude;
            while (true) {
                int event = parser.next();
                if (event == XMLStreamConstants.END_DOCUMENT) {
                    parser.close();
                    System.out.println("\nTOTAL STOPS " + stops + " \n");
                    outfile.close();
                    fis.close();
                    return;
                }
                String ElementName;

                if (event == XMLStreamConstants.START_ELEMENT) {
                    ElementName = parser.getLocalName();
                    if (ElementName.equals("Stop")) {
                        stopid = "";
                        lon = "";
                        lat = "";
                        name = "";
                        id = "";
                        landmark = "";
                        street = "";
                    }
                    if (ElementName.equals("ATCOCode")) {
                        while (event != XMLStreamConstants.END_ELEMENT) {
                            event = parser.next();
                            if (event == XMLStreamConstants.CHARACTERS) {
                                stopid = parser.getText().trim();
                            }
                        }
                    } else if (ElementName.equals("Lon")) {
                        while (event != XMLStreamConstants.END_ELEMENT) {
                            event = parser.next();
                            if (event == XMLStreamConstants.CHARACTERS) {
                                lon = parser.getText().trim();
                            }
                        }
                    } else if (ElementName.equals("Lat")) {
                        while (event != XMLStreamConstants.END_ELEMENT) {
                            event = parser.next();
                            if (event == XMLStreamConstants.CHARACTERS) {
                                lat = parser.getText().trim();
                            }
                        }
                    } else if (ElementName.equals("CommonName")) {
                        while (event != XMLStreamConstants.END_ELEMENT) {
                            event = parser.next();
                            if (event == XMLStreamConstants.CHARACTERS) {
                                name = parser.getText().trim();

                            }
                        }
                    } else if (ElementName.equals("Identifier")) {
                        while (event != XMLStreamConstants.END_ELEMENT) {
                            event = parser.next();
                            if (event == XMLStreamConstants.CHARACTERS) {
                                id = parser.getText().trim();
                            }
                        }
                    } else if (ElementName.equals("Street")) {
                        while (event != XMLStreamConstants.END_ELEMENT) {
                            event = parser.next();
                            if (event == XMLStreamConstants.CHARACTERS) {
                                street = parser.getText().trim();

                            }
                        }
                    } else if (ElementName.equals("Landmark")) {
                        while (event != XMLStreamConstants.END_ELEMENT) {
                            event = parser.next();
                            if (event == XMLStreamConstants.CHARACTERS) {
                                landmark = parser.getText().trim();
                            }
                        }
                    }
                    if (ElementName.equals("NatGaz")) {
                        longitude = Double.parseDouble(lon);
                        latitude = Double.parseDouble(lat);
                        if (pointInPolygon(points, latitude, longitude)) {
                            outfile.write("s" + stopid + "," + name + "," + landmark + " " + street + " " + id + "," + lat + "," + lon + "\n");
                            stops++;
                            //if(name.contains("Sea Mills")) {
                            //    System.out.println("+ Is in  :" + stopid + "," + name + "," + landmark + " " + street + " " + id + "," + lat + "," + lon );
                            //}
                        } else {
                            //if(name.contains("Sea Mills")) {
                            //    System.out.println("- Not in :" + stopid + "," + name + "," + landmark + " " + street + " " + id + "," + lat + "," + lon );
                            //}
                        }
                    }
                    //if(name.contains("Sea Mills")) {
                    //            System.out.println("  Skipped:" + stopid + "," + name + "," + landmark + " " + street + " " + id + "," + lat + "," + lon );
                    //}

                }
                //if (x%600 == 0) System.out.println(" ");
                x++;
            }
            //outfile.close();
            //parser.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static void generateTimes() {
        FileWriter fstream = null;
        BufferedReader br = null;
        try {
            fstream = new FileWriter("stopstimescomplex.txt");
            BufferedWriter outfile = new BufferedWriter(fstream);
            FileReader f = new FileReader("connections.csv");
            br = new BufferedReader(f);
            String times, tmp = "", row = "", duration = "";
            String id = "";


            while ((row = br.readLine()) != null) {
                String[] cells = row.split(",");
                Date present = null;
                DateFormat df = new SimpleDateFormat("HH:mm");
                int starthour = 8, endhour = 18;
                id = cells[0].trim() + cells[2].trim();
                int interval = Integer.parseInt(cells[5].trim());
                present = df.parse(cells[6].trim());
                Calendar c = Calendar.getInstance();
                c.setTime(present);
                String minute = "";
                int hour = c.get(Calendar.HOUR_OF_DAY);
                while (hour < endhour) {
                    minute = "" + c.get(Calendar.MINUTE);
                    if (c.get(Calendar.MINUTE) < 10) {
                        minute = "0" + c.get(Calendar.MINUTE);
                    }

                    outfile.write(id + "," + c.get(Calendar.HOUR_OF_DAY) + ":" + minute + ", " + cells[4] + ",Bus " + cells[1] + "\n");
                    c.add(Calendar.MINUTE, interval);
                    hour = c.get(Calendar.HOUR_OF_DAY);
                }

                tmp = cells[0];
                System.out.println("DONE: " + id);
            }
            outfile.close();
            System.out.println("FINISHED");
        } catch (Exception ex) {
            System.out.print(ex);
        } finally {
            try {
                fstream.close();
            } catch (IOException ex) {
            }
        }
    }
}
